import { ipcMain } from 'electron'
import { getLogger } from '../logger/index'
import { getTdabsRequestService } from '../services/tdabs-request-service'

/**
 * 设置远程预约处理器
 *
 * @description 设置远程预约处理器，包括查询、取消、更新等操作
 */
export function setupRemoteAppointmentHandlers(): void {
  const logger = getLogger()
  const svc = getTdabsRequestService()

  ipcMain.handle('remote-appointment:query-by-ref', async (_e, refLast6: string) => {
    try { return await svc.queryByRef({ refLast6 }) }
    catch (e: any) { logger.error('query-by-ref 失败', e); return { success: false, error: e?.message || String(e) } }
  })

  ipcMain.handle('remote-appointment:query-by-id', async (_e, payload: { passport?: string, hkid?: string, license?: string }) => {
    try { return await svc.queryById(payload) }
    catch (e: any) { logger.error('query-by-id 失败', e); return { success: false, error: e?.message || String(e) } }
  })

  ipcMain.handle('remote-appointment:cancel-by-ref', async (_e, refLast6: string) => {
    try { return await svc.cancelByRef({ refLast6 }) }
    catch (e: any) { logger.error('cancel-by-ref 失败', e); return { success: false, error: e?.message || String(e) } }
  })

  ipcMain.handle('remote-appointment:update-timeslot', async (_e, payload: { refLast6: string, officeCode?: string, preferredDates?: string[], preferredTimes?: string[] }) => {
    try { return await svc.updateTimeslot(payload) }
    catch (e: any) { logger.error('update-timeslot 失败', e); return { success: false, error: e?.message || String(e) } }
  })

  ipcMain.handle('remote-appointment:batch-cancel', async (_e, refs: string[], options?: { concurrency?: number }) => {
    try {
      const logger = getLogger()
      logger.info('🪄 批量取消开始', { total: refs?.length || 0, options })
      const res = await svc.batchCancelByRefs(refs, options)
      logger.info('🪄 批量取消结束', { ok: res.ok, fail: res.fail, total: res.total })
      if (res.errors?.length)
        logger.warn('🪄 批量取消错误样本', { sample: res.errors.slice(0, 3) })
      if (res.warns?.length)
        logger.warn('🪄 批量取消验证提醒', { sample: res.warns.slice(0, 3) })
      return res
    }
    catch (e: any) { logger.error('batch-cancel 失败', e); return { success: false, total: refs?.length || 0, ok: 0, fail: refs?.length || 0, errors: refs.map(r => ({ ref: r, error: e?.message || String(e) })) } }
  })

  logger.info('✅ 远程预约（request）IPC 处理器注册完成')
}
